<template>
  <div class="announcement-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
          <div class="search-container">
            <el-input
              v-model="searchTitle"
              placeholder="搜索标题"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select 
              v-model="searchStatus" 
              placeholder="状态" 
              style="width: 120px; margin-right: 10px"
              clearable
              @change="handleSearch"
            >
              <el-option label="下线" :value="0" />
              <el-option label="发布" :value="1" />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAdd">新增公告</el-button>
          </div>
        </div>
      </template>

      <el-table :data="announcements.records" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="标题" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '发布' : '下线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '下线' : '发布' }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="announcements.total || 0"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑公告' : '新增公告'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="form.content" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'
import dayjs from 'dayjs'

const loading = ref(false)
const announcements = ref({ records: [], total: 0 })
const dialogVisible = ref(false)
const formRef = ref(null)
const searchTitle = ref('')
const searchStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const form = reactive({
  id: '',
  title: '',
  content: '',
  status: 0
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

const formatDate = (date) => {
  if (!date) return '-';
  
  try {
    // 处理数组格式的日期 [YYYY, M, DD, HH, mm, ss]
    if (Array.isArray(date)) {
      // 确保数组有足够的元素
      if (date.length >= 6) {
        const [year, month, day, hour, minute, second] = date;
        // 月份需要格式化为两位数，并且注意原始月份可能是从0开始（JavaScript）或从1开始
        const formattedMonth = String(month).padStart(2, '0');
        const formattedDay = String(day).padStart(2, '0');
        const formattedHour = String(hour).padStart(2, '0');
        const formattedMinute = String(minute).padStart(2, '0');
        const formattedSecond = String(second).padStart(2, '0');
        
        return `${year}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}:${formattedSecond}`;
      }
      // 如果数组格式不完整，则返回原始值
      return JSON.stringify(date);
    }
    
    // 尝试常规日期格式
    const dateObj = new Date(date);
    if (!isNaN(dateObj.getTime())) {
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      const hours = String(dateObj.getHours()).padStart(2, '0');
      const minutes = String(dateObj.getMinutes()).padStart(2, '0');
      const seconds = String(dateObj.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    
    // 如果既不是数组也不是有效日期，则返回原始值
    return date;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return date; // 发生错误时返回原始值
  }
}

const loadAnnouncements = async () => {
  try {
    loading.value = true
    const res = await request.get('/admin/announcements', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        title: searchTitle.value,
        status: searchStatus.value
      }
    })
    if (res.code === 200) {
      announcements.value = res.data
    }
  } catch (error) {
    console.error('Failed to load announcements:', error)
    ElMessage.error('加载公告列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadAnnouncements()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadAnnouncements()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadAnnouncements()
}

const resetForm = () => {
  form.id = ''
  form.title = ''
  form.content = ''
  form.status = 0
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await request.put(`/admin/announcements/${form.id}`, form)
          ElMessage.success('更新成功')
        } else {
          await request.post('/admin/announcements', form)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        loadAnnouncements()
      } catch (error) {
        console.error('Failed to save announcement:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

const handleToggleStatus = async (row) => {
  try {
    await request.put(`/admin/announcements/${row.id}`, {
      ...row,
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success(row.status === 1 ? '下线成功' : '发布成功')
    loadAnnouncements()
  } catch (error) {
    console.error('Failed to toggle status:', error)
    ElMessage.error('操作失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/admin/announcements/${row.id}`)
      ElMessage.success('删除成功')
      loadAnnouncements()
    } catch (error) {
      console.error('Failed to delete announcement:', error)
      ElMessage.error('删除失败')
    }
  })
}

loadAnnouncements()
</script>

<style scoped>
.announcement-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 